<template>
  <q-select
    v-bind="props"
    :options="innerOptions"
    :style="{ width: width ? width + 'px' : undefined }"
    @filter="filter"
    @update:model-value="(v) => emit('update:modelValue', v)"
  >
  </q-select>
</template>
<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { QSelect, QSelectProps } from 'quasar';

  interface AutocompleteProps extends Omit<QSelectProps, 'onUpdate:modelValue'> {
    filterAttrs?: string; // 过滤的属性，可多个通过逗号分隔
    width?: number | string;
  }

  const props = withDefaults(defineProps<AutocompleteProps>(), {
    outlined: true,
    useInput: true,
    emitValue: true,
    mapOptions: true,
    fillInput: true,
    hideSelected: true,
    error: undefined,
    inputDebounce: 200,
    clearable: true,
    filterAttrs: undefined,
    width: undefined,
  });
  const emit = defineEmits(['update:modelValue']);

  const innerOptions = ref(props.options);
  watch(
    () => props.options,
    () => {
      innerOptions.value = props.options;
    },
  );

  //实现过滤
  const filter = (val: string, update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void) => {
    if (!val || val === '' || val.trim() == '') {
      update(() => (innerOptions.value = props.options));
      return;
    }
    update(() => {
      const v = val.toLowerCase();
      innerOptions.value = props.options?.filter((o) => {
        if (typeof o == 'string') return o.toLowerCase().indexOf(v) > -1;
        else {
          if (props.filterAttrs) {
            let bl = false;
            props.filterAttrs.split(',').forEach((a) => {
              bl = bl || o[a]?.toLowerCase().indexOf(v) > -1;
            });
            return bl;
          } else {
            return o.label?.toLowerCase().indexOf(v) > -1 || o.data?.toLowerCase().indexOf(v) > -1;
          }
        }
      });
    });
  };
</script>
